<template>
  <lemon-imui ref="IMUI" style="width:100%;height:100%;scroll-y:scroll" :user="user_now" @send="sendMsg"
    @change-menu="menuReload" @pull-messages='handlePullMessages' @change-contact="changeContact" :hideDrawer="false" />
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'YChat',
  data() {
    return {
      ws: null,
      user_now: new Object(),
      pageNums: {

      },
      pageSize: 10,
      contact_now: null,
      contacts: null
    }
  },
  props: {
    drawer: {
      type: Boolean,
      required: true
    }
  },
  mounted() {
    this.__initUser()
    this.__initMenus()
    this.__initRooms()
    this.__initSocket()
    this.__initDrawer()
  },
  computed: {
    ...mapState('userAbout', ['token', 'user', 'userPersonality'])
  },
  methods: {
    __initUser() {
      const user = new Object()
      user.id = this.user.userId
      user.displayName = this.user.userName
      if (this.userPersonality) user.avatar = `http://172.30.233.181:9001/oss/icons/${this.userPersonality.userHeadsPath}`
      this.user_now = user;
    }
    ,
    __initRooms() {
      this.$basicAxios(this.$ms.get_room_list(this.token), (resp) => {
        this.contacts = this.transContacts(resp.data.data)
        this.$refs.IMUI.initContacts(this.contacts)
      })
    },
    __initSocket() {
      this.ws = this.$websocket.create_socket(this.token, this.onOpen, this.onMessage, this.onClose, this.onError)
    },
    __initMenus() {
      this.$refs.IMUI.initMenus([
        {
          name: "messages",
        },
        {
          name: "contacts",
        },
        {
          name: "custom1",
          title: "房间搜素",
          unread: 0,
          isButton: true,
          render: menu => {
            return <i class="el-icon-search" />;
          },
          renderContainer: () => {
            return (
              <Groups></Groups>
            )
          }
        },
        {
          name: "custom2",
          title: "建立房间",
          unread: 0,
          isButton: true,
          render: menu => {
            return <i class="el-icon-plus" />;
          },
          renderContainer: () => {
            return (
              <RoomBuild></RoomBuild>
            )
          }
        },
        {
          name: "custom3",
          title: "通知中心",
          unread: 0,
          isButton: true,
          render: menu => {
            return <i class="el-icon-message-solid" />;
          },
          renderContainer: () => {
            return (
              <YChatNotice></YChatNotice>
            )
          }
        },
        {
          name: "custom4",
          title: "房间管理",
          unread: 0,
          isButton: true,
          render: menu => {
            return <i class="el-icon-tickets" />;
          },
          renderContainer: () => {
            return (
              <GroupManage></GroupManage>
            )
          }
        }
      ])
    },
    transContacts(data) {
      for (let i = 0; i < data.length; i++) {
        const room = data[i]
        const obj = new Object()
        obj.id = room.roomId
        obj.displayName = room.roomName
        obj.index = room.roomName.substring(0, 1)
        obj.unread = room.unread
        if (room.lastMessage) {
          obj.lastSendTime = room.lastMessage.createTime
          obj.lastContent = room.lastMessage.messageContent
        }
        data[i] = obj
      }
      return data
    },
    transMsg(msg) {
      const obj = new Object()
      obj.id = msg.messageId
      obj.status = 'succeed'
      obj.type = 'text'
      obj.sendTime = msg.createTime
      obj.content = msg.messageContent
      obj.fromUser = { id: msg.createBy, displayName: msg.userName } // 显示
      obj.toContactId = msg.roomId // 消息显示地点
      return obj
    },
    onOpen() {
      console.log("服务器已连接")
    },
    onError() {
      console.log('网络出现错误')
    },
    onClose() {
      console.log('已断开连接')
    },
    onMessage(msg) {
      // 收到消息
      if (msg.data == '[ success ] 已成功连接上云顶') return
      const m = JSON.parse(msg.data)
      if (m.createBy == this.user.userId) return
      // 消息提醒
      if (!this.drawer) this.$message(`${m.userName}:${m.messageContent}`)
      const contact = this.$refs.IMUI.getCurrentContact()
      const msg_now = this.transMsg(m)
      this.$refs.IMUI.appendMessage(msg_now, true)
    },
    sendMsg(msg, next) {
      const to_msg = { messageContent: msg.content, roomId: msg.toContactId }
      this.$websocket.send_msg_to_room(this.ws, to_msg)
      next();
    },
    menuReload(name) {
      if (name == 'contacts') {
        // 群组的重载
        this.__initRooms()
      } else if (name == 'custom4') {
        this.$pubsub.publish('reloadManage')
      } else if (name == 'custom3') {
        this.$pubsub.publish('reloadNotice')
      }
    },
    handlePullMessages(contact, next) {
      // 拉取最新的消息
      if (this.contact_now) {
        // 加载最消息
        if (this.pageNums[contact.id] == undefined) {
          // 未定义 pageNums变化不需要重新渲染
          this.pageNums[contact.id] = 1
        }
        if (this.pageNums[contact.id] == 1) {
          // 更新未读消息数目 因为拉取了最新的消息
          this.$refs.IMUI.updateContact({ id: contact.id, unread: 0 })
        }
        // 更新读取消息的最新时间戳
        this.$basicAxios(this.$websocket.udpate_time(contact.id, new Date().getTime(), this.token))
        this.$basicAxios(this.$websocket.get_messages(contact.id, this.pageNums[contact.id], this.pageSize, this.token), (resp) => {
          const msgs = new Array()
          for (let i = 0; i < resp.data.data.length; i++) {
            const msg = resp.data.data[i]
            msgs.push(this.transMsg(msg))
          }
          msgs.reverse()
          if (msgs.length == this.pageSize) next(msgs, false) // 下次继续触发
          else next(msgs, true)
          this.pageNums[contact.id]++
        })
      }
      else next([], true)
    },
    changeContact(contact) {
      this.contact_now = contact
    },
    __initDrawer() {
      // this.$refs.IMUI.openDrawer({
      //   render: () => {
      //     return (
      //       <div class="drawer-content">
      //         <p>
      //           <b>自定义抽屉</b>
      //         </p>
      //       </div>
      //     );
      //   },
      // })
    }
  }
}
</script>
<style scoped lang="less">
/deep/.lemon-menu {
  background-color: #99CCCC;
}
</style>